package cn.edu.scau.cmil.linwei.comprehensive.Controller;

import cn.edu.scau.cmil.linwei.comprehensive.Script.*;
import cn.edu.scau.cmil.linwei.comprehensive.util.DataIO;
import cn.edu.scau.cmil.linwei.comprehensive.util.StageManager;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class TeacherReportWindowsController implements Initializable {
    public BorderPane borderPane;
    //显示学生成绩的tableView
    public TableView table;
    public TableColumn StudentIDTableColumn;//学号
    public TableColumn StudentNameTableColumn;//学生姓名
    public TableColumn AttendTableColumn;//考勤分
    public TableColumn ExamTableColumn;//测验分
    public TableColumn WorkTableColumn;//作业分
    public TableColumn FinalExamTableColumn;//期末分
    public TableColumn TotalScoreTableColumn;//总评
    //显示成绩区间的tableView
    public TableView parttable;
    public TableColumn sectionTableColumn;//成绩区间
    public TableColumn numberTableColumn;//人数
    public TableColumn percentTableColumn;//百分比


    public Text userIDText;
    public Text CourseNameText;
    public Text TeacherNameText;
    public Text ClassNameText;
    public Text TipText;


    //标题栏最小化、关闭、拖拽
    private double oldStageX,oldStageY,oldScreenX,oldScreenY;//点击时记录窗口的XY
    //最小化
    public void MinButtonClicked(){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.setIconified(true);
    }//设置最小化按钮点击时发生的活动选项
    //关闭
    public void CloseButtonClicked(){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.close();
    }//设置关闭按钮点击时发生的活动选项
    //鼠标拖拽
    public void MousePressed(MouseEvent event){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        oldStageX = stage.getX();//事件相对于MouseEvent源的原点的水平位置，即获取当前鼠标位置
        oldStageY = stage.getY();//事件相对于MouseEvent源的原点的垂直位置，即获取当前鼠标位置
        oldScreenX = event.getScreenX();//返回事件的绝对水平位置，即获取窗口左上角位置
        oldScreenY = event.getScreenY();//返回事件的绝对垂直位置，即获取窗口左上角位置
    }

    public void MouseDragged(MouseEvent event){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.setX(event.getScreenX()-oldScreenX+oldStageX);
        stage.setY(event.getScreenY()-oldScreenY+oldStageY);
    }

    //页面转换
    public void GoBack(){//返回教师主界面
        CloseTeacherReportWindows();//关闭当前界面
        openTeacherMainWindows();//打开教师主界面
    }//注销

    public void openTeacherMainWindows() {
        Stage stage = StageManager.STAGEMAP.get("TeacherMainWindows");
        StageManager.STAGEMAP.remove("TeacherMainWindows");//在MAP中删除TeacherMainWindows页面的Stage
        StageManager.CONTROLLERMAP.remove("TeacherMainWindows");//在MAP中删除TeacherMainWindows页面的Controller
        stage.show();
    }//打开主界面

    public void CloseTeacherReportWindows(){
        Stage stage = (Stage)borderPane.getScene().getWindow();//通过布局获取场景再获取舞台
        StageManager.STAGEMAP.put("TeacherReportWindows",stage);//保存舞台
        StageManager.CONTROLLERMAP.put("TeacherReportWindowsController",this);//保存控制器
        stage.close();//关闭舞台
    }//关闭本窗口

    //设置Text
    public void setUserIDText(){
        userIDText.setText(DataField.LoginedUser.Name);
    }//设置欢迎词

    public void setCourseNameText(String s){
        CourseNameText.setText("课程："+s);
    }//设置课名

    public void setTeacherNameText(String s){
        TeacherNameText.setText("教师："+s);
    }//设置教师名

    public void setClassNameText(String grade,String major,String classes){
        ClassNameText.setText("班级："+grade+"级"+major+"专业"+classes+"班");
    }//设置班级名

    public void setCourseNameAndTeacherNameAndClassName(){
        TeacherMainWindowsController controller =//拿到教师主页面的控制器
                (TeacherMainWindowsController) StageManager.CONTROLLERMAP.get("TeacherMainWindowsController");
        setCourseNameText(controller.getChoosedCourse());
        setTeacherNameText(DataField.LoginedUser.Name);
        setClassNameText(controller.getChoosedGrade(),controller.getChoosedMajor(),controller.getChoosedClass());
    }//设置课名、教师名、班级名

    //TableView表格数据操作
    //1.学生成绩主表格
    public final ObservableList<StudentData> Maindata = FXCollections.observableArrayList();
    public ArrayList<Score> SearchedScoredata;

    public void InitMainTable(){
        SearchedScoredata = new ArrayList<>();
        //设置七列，将数据关联到表中的列
        StudentIDTableColumn.setCellValueFactory(new PropertyValueFactory<>("StudentID"));//第一列中的数据关联StudentData中的StudentID
        StudentNameTableColumn.setCellValueFactory(new PropertyValueFactory<>("StudentName"));//第二列中的数据关联StudentData中的lastName
        AttendTableColumn.setCellValueFactory(new PropertyValueFactory<>("Attend"));
        ExamTableColumn.setCellValueFactory(new PropertyValueFactory<>("Exam"));
        WorkTableColumn.setCellValueFactory(new PropertyValueFactory<>("Work"));
        FinalExamTableColumn.setCellValueFactory(new PropertyValueFactory<>("FinalExam"));
        TotalScoreTableColumn.setCellValueFactory(new PropertyValueFactory<>("TotalScore"));
        table.setItems(Maindata);//数据关联到tableView
    }//初始化主表格

    public void SearchforMainTable(){
        //在ScoreData中查找课程、老师、年级、专业、班级都相同的学生信息，并add到data中，tableView会实时更新
        Score score;
        TeacherMainWindowsController controller =//拿到教师主页面的控制器
                (TeacherMainWindowsController) StageManager.CONTROLLERMAP.get("TeacherMainWindowsController");
        String course = controller.getChoosedCourse();
        String teachername = DataField.LoginedUser.Name;
        String grade = controller.getChoosedGrade();
        String major = controller.getChoosedMajor();
        String classes = controller.getChoosedClass();

        for(int i = 0; i<DataField.scoreData.size(); i++){
            score = DataField.scoreData.get(i);
            if(score.CourseName.equals(course) &&  score.TeacherName.equals(teachername) &&
                    score.StudentGrade.equals(grade) && score.StudentMajor.equals(major) && score.StudentClass.equals(classes)){
                //如果课程、老师、年级、专业、班级都相同，提取学号，姓名，考勤，测验，作业，期末
                //对总评=考勤+测验+作业+期末进行更新
                int total = score.Attend + score.Exam + score.Work + score.FinalExam;
                score.TotalScore = total;
                StudentData sd = new StudentData(score.StudentID,score.StudentName,
                        score.Attend,score.Exam,score.Work,score.FinalExam,score.TotalScore);
                //this.sd = sd ;
                //sc = score;
                SearchedScoredata.add(score);//把搜索到的学生信息添加进去，查找区间的时候用
                Maindata.add(sd);//把学生信息
            }
        }
        try {
            DataIO.ScoreWrite();//把更改的信息写入文件，否则更新的总评不会被保存下来
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//为主表格搜索数据

    //2.成绩区间表格
    public final ObservableList<PartScoreData> Partdata = FXCollections.observableArrayList();
    String[] sections = {"0-59","60-69","70-79","80-89","90-100"};
    int[] numbers = {0 , 0 , 0 , 0 , 0};
    double[] percents = {0.0 , 0.0 , 0.0 , 0.0 , 0.0};

    public void InitPartTable(){
        //设置三列，将数据关联到表中的列
        sectionTableColumn.setCellValueFactory(new PropertyValueFactory<>("section"));//第一列中的数据关联PartScoreData中的section
        numberTableColumn.setCellValueFactory(new PropertyValueFactory<>("number"));//第二列中的数据关联PartScoreData中的number
        percentTableColumn.setCellValueFactory(new PropertyValueFactory<>("percent"));

        parttable.setItems(Partdata);//数据关联到tableView
    }

    public void SearchforPartTable(){
        //在SearchedScoredata中统计各区间的人数，并计算出百分比，add到data中，tableView会实时更新
        Score score;
        for(int i = 0; i<SearchedScoredata.size(); i++){
            score = SearchedScoredata.get(i);

            if(score.TotalScore<=59){
                numbers[0]++;
            }
            else if(score.TotalScore<=69){
                numbers[1]++;
            }
            else if(score.TotalScore<=79){
                numbers[2]++;
            }
            else if(score.TotalScore<=89){
                numbers[3]++;
            }
            else{
                numbers[4]++;
            }
            double totalnumber = 0;
            for(int n:numbers){
                totalnumber+=(double)n;
            }
            for(int j =0 ; j<percents.length ; j++){
                int x = (int)((double) numbers[j]/totalnumber*1000+0.5);//(int)(76.9+0.5)
                percents[j]=(double)x/10;
            }
        }//for
        for(int i =4;i>=0;i--){
            PartScoreData tmp = new PartScoreData(sections[i],numbers[i],Double.valueOf(percents[i])+"%");
            Partdata.add(tmp);//把学生信息
        }
    }

    //生成成绩文件
    public void CreateReportFile() throws IOException {
        System.out.println("CreateReportFile");
        TeacherMainWindowsController controller =//拿到教师主页面的控制器
                (TeacherMainWindowsController) StageManager.CONTROLLERMAP.get("TeacherMainWindowsController");
        String courseName = controller.getChoosedCourse();
        String teacherName = DataField.LoginedUser.Name;
        StudentClass studentClass = new StudentClass(controller.getChoosedGrade(),controller.getChoosedMajor(),controller.getChoosedClass());
        //文件名为"教师名-课程名-年级-专业-班级"
        String filename = teacherName+"-"+courseName+"-"+
                studentClass.StudentGrade+"级"+studentClass.StudentMajor+studentClass.StudentClass+"班.txt";
        System.out.println(filename);
        File file = new File("ReportFile/",filename);
        file.createNewFile();
        try{
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write("期末考试成绩单");
            bufferedWriter.newLine();bufferedWriter.newLine();
            bufferedWriter.write("课程："+courseName);
            bufferedWriter.newLine();
            bufferedWriter.write("教师："+teacherName);
            bufferedWriter.newLine();
            bufferedWriter.write("班级："+studentClass.StudentGrade+"级"+studentClass.StudentMajor+studentClass.StudentClass+"班");
            bufferedWriter.newLine();bufferedWriter.newLine();
            bufferedWriter.write("学号\t\t姓名\t\t考勤\t测验\t作业\t期末\t总评\t");
            bufferedWriter.newLine();
            for(Score score:SearchedScoredata){
                int totalscore = score.Attend+score.Exam+score.Work+score.FinalExam;
                bufferedWriter.write(score.StudentID+"\t"+score.StudentName+"\t"+
                        score.Attend+"\t"+score.Exam+"\t"+score.Work+"\t"+score.FinalExam+"\t"+totalscore);
                bufferedWriter.newLine();
            }
            bufferedWriter.newLine();
            bufferedWriter.write("成绩区间\t人数\t百分比");
            bufferedWriter.newLine();
            for(int i = 0;i<5;i++){
                bufferedWriter.write(sections[i]+"\t\t"+numbers[i]+"\t"+percents[i]+"%");
                bufferedWriter.newLine();
            }


            bufferedWriter.close();
            fileWriter.close();
        }

        catch (IOException e){
            TipText.setText("生成失败\n"+e.getMessage());
            return;
        }
        TipText.setText("生成成功，文件在根目录下的ReportFile文件夹内\n文件名为：\""+filename+"\"");
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {//初始化函数在执行FXMLLoader时执行
        setUserIDText();
        setCourseNameAndTeacherNameAndClassName();
        TipText.setText("");

        InitMainTable();
        SearchforMainTable();

        InitPartTable();
        SearchforPartTable();

    }
}